
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;


import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class HowEver {


    public static void main(String[] args) {
        AtomicInteger i = new AtomicInteger(0) ;
        CountDownLatch lock = new CountDownLatch(1);
        CountDownLatch clock = new CountDownLatch(1);

        ZooKeeper zooKeeper;
        try {
             zooKeeper= new ZooKeeper(
                    "master:2181", 3600, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    i.getAndIncrement();
                    debug(watchedEvent,i);
                    lock.countDown();

                }
            },false);
            lock.await();
            System.out.println("-------begin to create ------");
            String t = zooKeeper.create("/stick", "win".getBytes()
                    , ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("?? s? created "+t);
            System.out.println("-------begin to sub and listen ------");
            byte[] j = zooKeeper.getData("/document", new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    i.getAndIncrement();
                    clock.countDown();
                    debug(event, i);
                }
            }, null);
            System.out.println("???data ?? get ?? "+new String(j));
            System.out.println("-------begin to set and listen ------");
            Stat exists = zooKeeper.exists("/document", true);

            zooKeeper.setData("/document","powerpoint".getBytes(),exists.getVersion());
            clock.await();
            System.out.println("end main");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }


    }
    public static void debug(WatchedEvent event,AtomicInteger i){
        System.out.println(Thread.currentThread().getName()
                +" : "+i +" : "
                + event);
    }
}
